import { LockOutlined, UserOutlined, BulbTwoTone } from '@ant-design/icons';
import { Alert, Tabs, message, Card, Form, Input, Button } from 'antd';
import React, { useState, useEffect } from 'react';
import ProForm, { ProFormCheckbox, ProFormText } from '@ant-design/pro-form';
import { useIntl, connect, FormattedMessage } from 'umi';
import type { Dispatch } from 'umi';
import type { StateType } from '@/models/login';
import type { LoginParamsType } from '@/services/login';
import type { ConnectState } from '@/models/connect';
import request from '@/utils/request';

import styles from './index.less';

export type LoginProps = {
  dispatch: Dispatch;
  userLogin: StateType;
  submitting?: boolean;
};

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC<LoginProps> = (props) => {
  const { userLogin = {}, submitting } = props;
  const { status, type: loginType } = userLogin;
  const [type, setType] = useState<string>('account');
  const [loading, setLoading] = useState<boolean>(false);
  const [timer, setTimer] = useState<number>(0);
  const [veriCode, setVeriCode] = useState<string>('1234');
  const [phonenumber, setPhonenumber] = useState<string>('');  
  const intl = useIntl();
  const [submitTxt, setSubmitTxt] = useState<string>(intl.formatMessage({id:'pages.login.submit'}));
  const registTxt = intl.formatMessage({id:'pages.regist.after.default'});

  const handleSubmit = (values: LoginParamsType) => {
    if (type === 'account') {
      const { dispatch } = props;
      setLoading(true);
      dispatch({
        type: 'login/login',
        payload: { ...values, type },
      }).then(() => {
        setLoading(false);
      });
    } else {
      setLoading(true);
      setSubmitTxt('账号注册中...，大概需要1~3分钟，请耐心等待！');
      if (veriCode != values.veriCode) {
        message.error('验证码错误！');
        setLoading(false);
        return;
      }
      values.name = values.tenancyName;
      request('/api/services/app/TenantAndUser/Register', {
        method: 'POST',
        data: values,
      }).then((response) => {
        if (response && response.success) {
          message.success('恭喜，注册成功!现在可以登录啦。');          
        } else {
          message.error(response.error?.message);
        }
        setLoading(false);
        setSubmitTxt(intl.formatMessage({id:'pages.login.submit'}));
      });
    }
  };
  const sendVeryCode = (seconds: number) => {
    setTimer(seconds);
    request('/api/services/app/Sms/SendVeriCode', {
      method: 'POST',
      data: {
        templateCode: 'SMS_235495512',
        phoneNumbers: phonenumber,
      },
    }).then((response) => {
      setVeriCode(response?.result);
    });
  };
  useEffect(() => {
    if (timer > 0) {
      setTimeout(() => {
        setTimer((count) => count - 1);
      }, 1000);
    }
  }, [timer,registTxt]);
  
  return (
    <div className={styles.main}>
      <Card>
        <ProForm
          initialValues={{
            autoLogin: true,
            tenant: 'Default',
          }}
          layout="horizontal"
          labelCol={{ span: 6 }}
          isKeyPressSubmit={true}
          submitter={{
            render: (_, dom) => dom.pop(),
            submitButtonProps: {
              loading: loading,
              size: 'large',
              style: {
                width: '100%',
              },
            },
            searchConfig: {
              submitText: (
                <span>
                  {submitTxt}
                </span>
              ),
            },
          }}
          onFinish={(values) => {
            handleSubmit(values as LoginParamsType);
            return Promise.resolve();
          }}
        >
          <Tabs activeKey={type} onChange={setType}>
            <Tabs.TabPane
              key="account"
              tab={intl.formatMessage({
                id: 'pages.login.accountLogin.tab',
                defaultMessage: 'Account password login',
              })}
            />
            <Tabs.TabPane
              key="regist"
              tab={intl.formatMessage({
                id: 'pages.login.accountRegist.tab',
                defaultMessage: 'Account regist',
              })}
            />
          </Tabs>

          {status === 500 && !submitting && loginType == 'account' && (
            <LoginMessage
              content={intl.formatMessage({
                id: 'pages.login.accountLogin.errorMessage',
                defaultMessage: 'Incorrect account or password',
              })}
            />
          )}
          {type === 'account' && (
            <>
              <ProFormText
                name="tenant"
                placeholder="Account: Default"
                fieldProps={{
                  size: 'large',
                  prefix: <BulbTwoTone className={styles.prefixIcon} />,
                }}
              />
              <ProFormText
                name="userNameOrEmailAddress"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.username.placeholder',
                  defaultMessage: 'Username: admin or user',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.username.required"
                        defaultMessage="Please enter user name!"
                      />
                    ),
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.password.placeholder',
                  defaultMessage: 'Password: 123456',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.password.required"
                        defaultMessage="Please enter password!"
                      />
                    ),
                  },
                ]}
              />
              <div
                style={{
                  marginBottom: 24,
                }}
              >
                <ProFormCheckbox noStyle name="autoLogin">
                  <FormattedMessage id="pages.login.rememberMe" defaultMessage="Auto login" />
                </ProFormCheckbox>
              </div>
            </>
          )}

          {type === 'regist' && (
            <>
              <Alert
                message={registTxt}
                type="warning"
                closable
                style={{ marginBottom: 16 }}
              />
              <ProFormText
                label={<FormattedMessage id="pages.regist.tenancy" defaultMessage="Tenancy" />}
                name="tenancyName"
                placeholder={intl.formatMessage({id: 'pages.regist.tenancy.tip'})}
                rules={[
                  {
                    required: true,
                    pattern: /^[a-zA-Z]([-_a-zA-Z0-9]{5,11})$/,
                    message: (
                      <FormattedMessage
                        id="pages.tenancy.required"
                        defaultMessage="Please enter tenancy"
                      />
                    ),
                  },
                ]}
              />

              <ProFormText
                name="adminEmailAddress"
                label={<FormattedMessage id="pages.regist.email" defaultMessage="Email" />}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.regist.email.required"
                        defaultMessage="please enter email!"
                      />
                    ),
                    pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                label={<FormattedMessage id="pages.regist.password" defaultMessage="Password" />}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.regist.password.required"
                        defaultMessage="Please enter password!"
                      />
                    ),
                  },
                ]}
              />
              <Form.Item
                label={<FormattedMessage id="pages.regist.telphone" defaultMessage="Telphone" />}
                style={{ marginBottom: 0 }}
                required
              >
                <Input.Group compact>
                  <Form.Item
                    name="telphone"
                    rules={[
                      {
                        required: true,
                        message: (
                          <FormattedMessage
                            id="pages.login.telphone.required"
                            defaultMessage="Please enter telphone!"
                          />
                        ),
                      },
                    ]}
                  >
                    <Input onChange={(e: any) => setPhonenumber(e.target.value)} />
                  </Form.Item>
                  <Form.Item>
                    <Button
                      type="default"
                      disabled={timer > 0 || phonenumber === ''}
                      onClick={() => sendVeryCode(60)}
                    >
                      {timer > 0 ? (
                        timer + ' s'
                      ) : (
                        <FormattedMessage id="pages.sendVeriCode" defaultMessage="Send Code" />
                      )}
                    </Button>
                  </Form.Item>
                </Input.Group>
              </Form.Item>
              <ProFormText
                name="veriCode"
                label={<FormattedMessage id="pages.regist.veriCode" defaultMessage="VeriCode" />}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.regist.veriCode.required"
                        defaultMessage="Please enter veriCode!"
                      />
                    ),
                  },
                ]}
              />
              <ProFormText
                name="company"
                label={<FormattedMessage id="pages.company.name" defaultMessage="Company" />}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.company.name.required"
                      />
                    ),
                  },
                ]}
              />
            </>
          )}
        </ProForm>
      </Card>
    </div>
  );
};

export default connect(({ login, loading }: ConnectState) => ({
  userLogin: login,
  submitting: loading.effects['login/login'],
}))(Login);
